<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <h1>品牌管理</h1>
        <el-divider></el-divider>
        <h3>品牌数量:{{$store.getters.brandCount}}</h3>
      </div>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-input v-model.trim="brandName" type="text" placeholder="请输入品牌列表" />
        </el-col>
        <el-col :span="4">
          <el-button @click="submit" type="primary">立即提交</el-button>
        </el-col>
      </el-row>
      <el-divider>分割线</el-divider>
      <el-table :data="$store.state.brandList" height="450" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="180"></el-table-column>
        <el-table-column prop="name" label="品牌名称" width="180"></el-table-column>
        <el-table-column prop="ctime" label="添加时间"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button @click="getBrand(scope.row)" type="success" round size="small" icon="el-icon-edit">编辑</el-button>
            <el-button @click="del(scope.row.id)" type="danger" round size="small" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  created(){
    // console.log(this.$store)
    // this.$store.commit('brandInit')
    // this.$store.dispatch: 触发actions中的异步方法
    this.$store.dispatch('getBrandList')
  },
  data() {
    return {
      // 品牌名称
      brandName:'',
      // 当前被编辑的品牌id
      id:''
    }
  },
  methods:{
    getBrand(row){
      // console.log(row)
      this.brandName=row.name
      this.id=row.id
    },
    del(id){
      // 通过this.$store.commit('方法名','额外参数')来触发mutations中的方法
      // this.$store.commit('brandDel',id)
      this.$store.dispatch('delBrand',id)
    },
    submit(){
      if(this.brandName===''){
        return this.$error('请输入品牌名称')
      }
      //  更新
      if(this.id>0){
        this.update()
      }else{  //  新增
        this.add()
      }
    },
    // 品牌新增
    add(){
      // 通过this.$store.commit('方法名','额外参数')来触发mutations中的方法
      // this.$store.commit('brandAdd',this.brandName)
      this.$store.dispatch('addBrand',this.brandName)
      // 重置表单
      this.brandName=''
    },
    // 品牌更新
    update(){
        // this.$store.commit('brandUpdate',{id:this.id,name:this.brandName})
        this.$store.dispatch('updateBrand',{id:this.id,name:this.brandName})
        // 重置表单
        this.brandName=''
        this.id=''
    }
  }
}
</script>

<style>
</style>